new Vue({

  el: '#app',

  data: {
    inputDevices: [],
    selectedDeviceIndex: 0,
    stream: null,
    isRecording: false,
    isPaused: false,
    videoConstraints: {
      width: 100,
      height: 100,
    },
    messages: [],
    unSubmitMessage: '',
    ws: null,
  },

  async mounted() {
    this.getDevices();

    this.ws = new WebSocket('ws://localhost:8888');
    this.ws.onmessage = e => {
      const message = JSON.parse(e.data);
      this.messages.push(message);
    };
  },

  computed: {
    startBtnDisabled() {
      return this.isRecording;
    },
    pauseBtnDisabled() {
      return !this.isRecording || this.isPaused;
    },
    resumeBtnDisabled() {
      return !this.isRecording || !this.isPaused;
    },
    stopBtnDisabled() {
      return !this.isRecording;
    }
  },

  watch: {
    messages: function() {
      this.$nextTick().then(() => {
        const el = this.$refs.messageView;
        el.scrollTo(el.scrollLeft, el.scrollHeight);
      });
    },
  },

  methods: {
    async getDevices() {
      const devices = await navigator.mediaDevices.enumerateDevices();
      this.inputDevices = devices.filter(device => device.kind === 'audioinput' || device.kind === 'videoinput');
    },

    async startRecord() {
      this.isRecording = true;
      this.isPaused = false;
      this.stream = await navigator.mediaDevices.getUserMedia({ video: {}, audio: false });
      this.$refs.preview.srcObject = this.stream;
    },

    async pauseRecord() {
      this.isPaused = true;
    },

    async resumeRecord() {
      this.isPaused = false;
    },

    async stopRecord() {
      this.isRecording = false;
      this.isPaused = false;
      this.$refs.preview.srcObject = null;
      this.stream.getTracks().forEach(track => track.stop());
    },

    sendMessage() {
      if (this.unSubmitMessage.length) {
        const message = {
          name: 'Self',
          content: this.unSubmitMessage,
        };
        this.unSubmitMessage = '';
        this.ws.send(JSON.stringify(message));
      }
    },
  },

});
